package com.yc.forum.servlet;

import com.yc.forum.dao.RedisDao;
import com.yc.forum.dao.ReplyDao;
import com.yc.forum.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//查询评论,包括评论，发布者，点赞、评论数量
@WebServlet(name = "QueryReplyServlet", value = "/QueryReplyServlet.s")
public class QueryReplyServlet extends HttpServlet {
    ReplyDao replyDao=new ReplyDao();
    RedisDao redisDao=new RedisDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("------init queryReplyServlet.java----------");
        String postId=req.getParameter("postId");
        int begin=Integer.parseInt(req.getParameter("begin"));
        int size=Integer.parseInt(req.getParameter("size"));
        //查询到评论和发布者详情
        List<Map<String,Object>> replies=replyDao.selectReplyWithLimitOrderByTime(postId,begin,size);
        //查询评论点赞数、评论数，并拼接到对应的repls中，然后添加到newReplies中
        List<Map<String,Object>> newReplies=new ArrayList<>();
        for(Map<String,Object> reply : replies){
            Map<String,String> someSum=redisDao.queryReplySomeSumById(""+reply.get("id"));
            //将点赞量、评论量拼接到reply中
            reply.put("likesum",someSum.get("likesum"));
            reply.put("commentsum",someSum.get("commentsum"));



            newReplies.add(reply);
        }

        List<Map<String,Object>> newnewReplies=new ArrayList<>();
        HttpSession session= req.getSession();
        String account;
        try{
            account=session.getAttribute("loginedUser").toString();

            for(Map<String,Object> reply:newReplies){
                //评论id
                String replyid=""+reply.get("id");
                //给该评论点赞人的id集合
                List<String> listaccount=redisDao.queryReplySuppAccount(replyid);
                System.out.println("supportlist"+listaccount);
                //判断是否存在
                int a= listaccount.lastIndexOf(account);
                System.out.println("a="+a);

                if(a>=0){
                    a=1;
                }else{
                    a=-1;
                }
                reply.put("isSupport",a);
                newnewReplies.add(reply);
            }
        }catch(Exception e){
            for(Map<String,Object> reply:newReplies){
                reply.put("isSupport",-1);
                newnewReplies.add(reply);
            }
        }

        System.out.println("newnewreplies="+newnewReplies);

        Utils.toJson(newnewReplies,resp);
    }
}
